package com.software.project.service;

import com.software.project.entity.User;
import com.software.project.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public User findUserById(String id) {
        log.debug("id: {}", id);
        Optional<User> byId = userRepository.findById(id);
        if (byId.isPresent()) {
            log.debug("user: {}", byId.get());
            return byId.get();
        } else {
            log.debug("user: {}", "null");
            return null;
        }
    }

    @Override
    public User createUser(User user) {
        log.debug("user: {}", user);
        if (user.getUserId() == null) {
            user.setUserId(UUID.randomUUID().toString());
        }
        User save = userRepository.save(user);
        log.debug("user: {}", save);
        return save;
    }

    @Override
    public User checkUserName(String userName) {
        log.debug("userName: {}", userName);
        Optional<User> byUserName = userRepository.findByUserName(userName);
        if (byUserName.isPresent()) {
            log.debug("user: {}", byUserName.get());
            return byUserName.get();
        } else {
            log.debug("user: {}", "null");
            return null;
        }
    }

    @Override
    public User checkPassword(String userName, String password) {
        log.debug("userName: {}, password: {}", userName, password);
        Optional<User> byUserName = userRepository.findByUserName(userName);
        if (byUserName.isPresent() && byUserName.get().getPassword().equals(password)) {
            log.debug("user: {}", byUserName.get());
            return byUserName.get();
        } else {
            log.debug("user: {}", "null");
            return null;
        }
    }
}
